<template>
  <div class="introduction-edit-page">
    <!-- Tab 栏 -->
    <a-tabs v-model="activeTab" @change="handleTabChange" v-if="false">
      <a-tab-pane key="zh" title="中文"></a-tab-pane>
      <a-tab-pane key="en" title="英文"></a-tab-pane>
      <a-tab-pane key="ja" title="日语"></a-tab-pane>
      <a-tab-pane key="ko" title="韩语"></a-tab-pane>
    </a-tabs>

    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <a-form-item  field="introduction_text">
        <ma-wangEditor v-model="formData.introduction_text" :height="400" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="submit">保存</a-button>
        <a-button style="margin-left: 10px;" @click="emit('close')">关闭</a-button>
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import api from '../api/introduction'

const emit = defineEmits(['success', 'close'])
const props = defineProps({
  // 接收要编辑的数据
  editData: {
    type: Object,
    required: true
  }
})

// 引用定义
const formRef = ref()
const loading = ref(false)
const activeTab = ref('zh') // 默认选中中文

// 表单信息
const formData = reactive({
  introduction_text: '',
  lang_code: ""
})

// 统一验证规则
const rules = {
  introduction_text: [
    { required: true, message: '请输入园区介绍详情', trigger: 'blur' }
  ]
}

// 初始化页面数据
const initPage = async () => {
  try {
    const result = await api.readDetail(activeTab.value)
    if (result.code === 200) {
      const data = result.data
      // 将接口返回的数据赋值给表单数据
      formData.introduction_text = data.introduction_text || ''
      formData.lang_code = data.lang_code || activeTab.value
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// Tab 切换处理
const handleTabChange = async (key) => {
  activeTab.value = key
  // 设置语言代码
  formData.lang_code = key

  try {
    const result = await api.readDetail(key)
    if (result.code === 200) {
      const data = result.data
      // 将接口返回的数据赋值给表单数据
      formData.introduction_text = data.introduction_text || ''
      formData.lang_code = data.lang_code || key
    }
  } catch (error) {
    console.error('切换语言获取数据失败:', error)
  }
}

// 数据保存
const submit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    const result = await api.save(formData)
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
}

onMounted(() => {
  // 初始化时设置默认语言的 lang_code
  handleTabChange(activeTab.value)
})

defineExpose({ submit })
</script>

<style scoped>
.introduction-edit-page {
  padding: 20px;
}
</style>